package com.atguigu.crowd.service.impl;


import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseException;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.until.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import crowd.entity.Admin;
import crowd.entity.AdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {

        // 将密码加密
        String Pswd = admin.getUserPswd();
        Pswd = passwordEncoder.encode(Pswd);
        admin.setUserPswd(Pswd);

        // 生成创建时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String creatTime = format.format(date);
        admin.setCreateTime(creatTime);

        adminMapper.insert(admin);
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        // 根据登陆账号查询Admin对象
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andLoginAcctEqualTo(loginAcct);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        // 判断查询到的对象是否为空或者是否为多个对象，为否则抛出异常
        if (adminList == null || adminList.size() == 0){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (adminList.size() > 1){
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }

        Admin admin = adminList.get(0);
        // 如果admin对象为空，则抛出异常
        if (admin == null){
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        // 将数据库中的密码取出
        String userPswdDB = admin.getUserPswd();

        // 将表单提交的密码进行加密
        String userPswdFrom = CrowdUtil.md5(userPswd);

        // 将两者密码进行比较
        if (!Objects.equals(userPswdDB, userPswdFrom)){
            // 如果不相等，抛出异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }

        //全部一致则返回admin对象
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 开启分页功能
        PageHelper.startPage(pageNum, pageSize);

        // 执行查询语句
        List<Admin> adminList = adminMapper.selectAdminByKeyword(keyword);

        // 封装到PageInfo中
        return new PageInfo<>(adminList);
    }

    @Override
    public void removeAdmin(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAdminById(Integer adminId) {

        Admin admin = adminMapper.selectByPrimaryKey(adminId);

        return admin;
    }

    @Override
    public void updateAdmin(Admin admin) {
        // 根据admin更新用户数据，如果为null值则保持原值
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            // 如果违反账号唯一性原则，则抛出此自定义异常
            if (e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseForUpdateException(CrowdConstant.MESSAGE_LOGIN_ALREADY_IN_USE);
            }
        }

    }

    @Override
    public void saveAdminAndRoleRelationship(Integer adminId, List<Integer> roleIdList) {
        // 删除所有旧的角色
        adminMapper.deleteOldRelationship(adminId);

        // 再添加新的角色
        if (roleIdList != null && roleIdList.size() != 0){

            adminMapper.insertNewRelationship(adminId, roleIdList);
        }

    }

    @Override
    public Admin getAdminByLoginAcct(String usename) {

        // 创建Example的查询条件
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andLoginAcctEqualTo(usename);

        // 获取Admin对象
        List<Admin> adminList = adminMapper.selectByExample(adminExample);
        Admin admin = adminList.get(0);

        return admin;

    }
}
